
import { gameConfigHandle } from "core/config/gameConfig"
import adventureHandle from "core/handle/adventureHandle"
import bagHandle from "core/handle/bagHandle"
import equipmentHandle from "core/handle/equipmentHandel"
import gemHandle from "core/handle/gemHandle"
import luckHandle from "core/handle/luckHandle"
import playerHandle from "core/handle/playerHandle"
import skillHandle from "core/handle/skillHandle"
import taskHandle from "core/handle/taskHandle"
import { ItemModel } from "core/model/itemModel"
import { PlayerModel } from "core/model/playerModel"
import { NormlaTaskType, RewardType } from "core/typeDefine/typeDefine"
import gameUtils from "core/utils/gameUtils"

import { GameRouteData, GameTime, localApi } from "core/utils/localApi"
import Random from "core/utils/random"
import utils from "core/utils/utils"


class PlayerRoute {

    @localApi("playerRoute")
    initPlayer(gameRouteData?: GameRouteData) {
        let { player, random,isMonthVip,isYearVip } = gameRouteData
        gameRouteData.player = new PlayerModel(player)
        playerHandle.initPlayer(gameRouteData.player,isMonthVip,isYearVip)
        return { err: 0 }
    }

    //寻宝随机事件
    @localApi("playerRoute")
    xubaoStepGift(active: number, gamRouteData?: GameRouteData) {
        // let { player, time, dayTime, random } = gamRouteData
        // let mapName = gameConfigHandle.gameConfig.luck.xunBaoMap[active]
        // let eventsConfig = gameConfigHandle.gameConfig.luck.xunbaoEvents
        // let event = utils.getOneFromArray(eventsConfig[mapName].events, random)
        // if (event['getItem'] == 'exp') {
        //     player.itemInfo.exp += event['amount']
        // } else if (event['getItem'] == 'money') {
        //     player.itemInfo.gold += event['amount']
        // }
        return { err: 0, data: event }
    }

    //寻宝行动
    @localApi("playerRoute")
    moveXunbao(gamRouteData?: GameRouteData) {
        // let { player, time, dayTime, random } = gamRouteData
        // let xunbao = player.luck.xunbao
        // let cheatNeedStep = gameConfigHandle.gameConfig.luck.cheapNeedSteps
        // let vip = playerHandle.getVip(player).vipLvl
        // let xbTlConfig = gameConfigHandle.gameConfig.luck.xbTlMax
        // let tlMax = utils.getIncValues(xbTlConfig, vip)
        // if (!xunbao.begin) {
        //     return { err: 100 }
        // }
        // let step = xunbao.step
        // let addTl = xunbao.addTl
        // if (xunbao.tl >= tlMax + addTl) {
        //     xunbao.begin = false
        //     return { err: 0 }//体力耗尽
        // }
        // let maxDiceNum = 0
        // let totalNum = 0
        // let allEqual = true
        // let diceNums = [random.intn(6), random.intn(6), random.intn(6)]
        // let cheatAmount = xunbao.cheats.length
        // for (let i = 0; i < diceNums.length; i++) {
        //     totalNum += diceNums[i]
        //     if (diceNums[i] > maxDiceNum) {
        //         maxDiceNum = diceNums[i]
        //     }
        //     if (i > 0 && diceNums[i] != diceNums[i - 1]) {
        //         allEqual = false
        //     }
        // }
        // step += maxDiceNum
        // let active = xunbao.active + maxDiceNum
        // if (active > 35) {
        //     active -= 36
        // }
        // let eggGiftConfig = gameConfigHandle.gameConfig.luck.xunbaoEggGift
        // //判断是否获得彩蛋
        // if (totalNum >= 15) {
        //     let gift = utils.getItemsByRate(eggGiftConfig, 1, random)[0]
        //     xunbao.eggs.push({ gift, haveGift: true })
        // }
        // if (allEqual) {
        //     let gift = utils.getItemsByRate(eggGiftConfig, 1, random)[0]
        //     xunbao.eggs.push({ gift, haveGift: true })
        // }
        // let toGetEggs = xunbao.toGetEggs
        // if (xunbao.toGetEggs.includes(active)) {
        //     toGetEggs = [utils.getRandomNumber(1, 9, random), utils.getRandomNumber(10, 18, random),
        //     utils.getRandomNumber(19, 27, random), utils.getRandomNumber(28, 35, random)]
        //     let gift = utils.getItemsByRate(eggGiftConfig, 1, random)[0]
        //     xunbao.eggs.push({ gift, haveGift: true })
        // }

        // //随机事件
        // let luckConfig = gameConfigHandle.gameConfig.luck
        // let mapName = luckConfig.xunBaoMap[active]
        // let eventsConfig = luckConfig.xunbaoEvents[mapName]
        // let event = utils.getOneFromArray(eventsConfig, random)
        // let itemId = event['getItem']
        // let amount = event['amount']
        // if (itemId == 'exp' || itemId == 'gold') {
        //     player.itemInfo[itemId] += amount * taskHandle.getResourcePerTimes(player, itemId)
        // } else if (itemId == 'power') {
        //     // xunbao.tl -= amount
        //     addTl += amount
        // } else if (itemId == 'step') {
        //     step += amount
        // }
        // //判断宝箱
        // let cheatAmountNow = Math.floor(step / cheatNeedStep)
        // let add = cheatAmountNow - cheatAmount
        // let cheatGiftConfig = gameConfigHandle.gameConfig.luck.xunbaoGift
        // if (add > 0) {
        //     for (let i = 0; i < add; i++) {
        //         let gift = utils.getItemsByRate(cheatGiftConfig, 1, random)[0]
        //         xunbao.cheats.push({ gift, haveGift: true })
        //     }
        // } else if (add < 0) {
        //     for (let i = 0; i < -add; i++) {
        //         xunbao.cheats.splice(0, 1)
        //     }
        // }
        // xunbao.active = active
        // xunbao.diceNums = diceNums
        // xunbao.step = step
        // xunbao.addTl = addTl
        // xunbao.tl++
        // xunbao.toGetEggs = toGetEggs
        // // console.log(xunbao.cheats, xunbao.eggs)
        return { err: 0, data: event }
    }


    @localApi("playerRoute")
    startXunbao(gameRouteData?: GameRouteData) {
        // let { player, random, isMonthVip, vipLvl } = gameRouteData
        // let eggs = player.luck.xunbao.eggs
        // let cheats = player.luck.xunbao.cheats
        // let haveGiftToGet = false
        // for (let i = 0; i < eggs.length; i++) {
        //     if (eggs[i].haveGift) {
        //         haveGiftToGet = true
        //     }
        // }
        // for (let i = 0; i < cheats.length; i++) {
        //     if (cheats[i].haveGift) {
        //         haveGiftToGet = true
        //     }
        // }
        // if (haveGiftToGet) {
        //     return { err: 2 }//有礼物未领取
        // }
        // player.luck.xunbao.eggs = []
        // player.luck.xunbao.cheats = []
        // let xbTimesMax = adventureHandle.getxunbaoAmount(player, isMonthVip)

        // if (player.luck.xunbao.times >= xbTimesMax) {
        //     let xbDiamondTimesMax = adventureHandle.getxunbaoDiamondAmount(player, isMonthVip)
        //     if (player.luck.xunbao.diamondTimes >= xbDiamondTimesMax) {
        //         return { err: 1 }
        //     } else {
        //         let needConfig = gameConfigHandle.gameConfig.need
        //         let res = gameUtils.useNeedResource(player, needConfig.xunbao, 1)
        //         if (res !== 0) {
        //             return { err: 3 }
        //         }
        //     }
        //     player.luck.xunbao.diamondTimes++
        // } else {
        //     player.luck.xunbao.times++
        // }
        // player.luck.xunbao.tl = 0
        // player.luck.xunbao.step = 0
        // player.luck.xunbao.addTl = 0
        // player.luck.xunbao.begin = true
        // player.luck.xunbao.toGetEggs = [utils.getRandomNumber(1, 9, random), utils.getRandomNumber(10, 18, random),
        // utils.getRandomNumber(19, 27, random), utils.getRandomNumber(28, 35, random)]
        return { err: 0 }
    }

    @localApi("playerRoute")
    onekeyGetGifts(gamRouteData?: GameRouteData) {
        // let { player, time, dayTime, random } = gamRouteData
        // let eggs = player.luck.xunbao.eggs
        // let cheats = player.luck.xunbao.cheats
        // let gifts: any[] = []
        // for (let i = 0; i < cheats.length; i++) {
        //     if (!cheats[i].haveGift) {
        //         continue
        //     }
        //     let gift = cheats[i].gift
        //     //将获取的奖励放进背包
        //     let item: ItemModel = null
        //     if (gift['type'] == RewardType.Equipment) {
        //         item = equipmentHandle.create(player, random, { quality: gift['quality'] })
        //         let res = bagHandle.addItemComponent(player.equipmentBag, item)
        //         if (!res) {
        //             return { err: 0, code: 1, data: gifts }//装备背包已满
        //         }
        //     }
        //     if (gift['type'] == RewardType.Skill) {
        //         item = skillHandle.createBook(random, { quality: gift['quality'] })
        //         let res = bagHandle.addItemComponent(player.skillBag, item)
        //         if (!res) {
        //             return { err: 0, code: 2, data: gifts }//技能背包已满
        //         }
        //     }
        //     if (gift['type'] == RewardType.Prop) {
        //         let res = bagHandle.addItem(player.bag, gift['getItem'] as number, gift['amount'])
        //         if (!res) {
        //             return { err: 0, code: 3, data: gifts }//材料背包已满
        //         }
        //     }
        //     if (gift['type'] == RewardType.Resource) {
        //         let amount = gift['amount']
        //         if (gift['getItem'] != 'diamond') {
        //             amount *= taskHandle.getResourcePerTimes(player, gift['getItem'] as string)
        //         }
        //         player.itemInfo[gift['getItem']] += amount
        //     }
        //     player.luck.xunbao.cheats[i].haveGift = false
        //     gifts.push(gift)
        // }
        // for (let i = 0; i < eggs.length; i++) {
        //     if (!eggs[i].haveGift) {
        //         continue
        //     }
        //     let gift = eggs[i].gift
        //     //将获取的奖励放进背包
        //     let res = bagHandle.addItem(player.bag, gift['getItem'], gift['amount'])
        //     if (!res) {
        //         return { err: 0, code: 3, data: gifts }//材料背包已满
        //     }
        //     player.luck.xunbao.eggs[i].haveGift = false
        //     gifts.push(gift)
        // }
        // return { err: 0, data: gifts }
    }
    @localApi("playerRoute")
    openCheat(index, gamRouteData?: GameRouteData) {
        // let { player, time, dayTime, random } = gamRouteData
        // if (!player.luck.xunbao.cheats[index].haveGift) {
        //     return { err: 2 }
        // }
        // let gift = player.luck.xunbao.cheats[index].gift
        // //将获取的奖励放进背包
        // let item: ItemModel = null
        // if (gift['type'] == RewardType.Equipment) {
        //     item = equipmentHandle.create(player, random, { quality: gift['quality'] })
        //     let res = bagHandle.addItemComponent(player.equipmentBag, item)
        //     if (!res) {
        //         return { err: 1 }//装备背包已满
        //     }
        // }
        // if (gift['type'] == RewardType.Skill) {
        //     item = skillHandle.createBook(random, { quality: gift['quality'] })
        //     let res = bagHandle.addItemComponent(player.skillBag, item)
        //     if (!res) {
        //         return { err: 1 }//技能背包已满
        //     }
        // }
        // if (gift['type'] == RewardType.Prop) {
        //     let res = bagHandle.addItem(player.bag, gift['getItem'] as number, gift['amount'])
        //     if (!res) {
        //         return { err: 1 }//材料背包已满
        //     }
        // }
        // if (gift['type'] == RewardType.Resource) {
        //     let amount = gift['amount']
        //     if (gift['getItem'] != 'diamond') {
        //         amount *= taskHandle.getResourcePerTimes(player, gift['getItem'] as string)
        //     }
        //     player.itemInfo[gift['getItem']] += amount
        // }
        // player.luck.xunbao.cheats[index].haveGift = false
        // return { err: 0, data: gift }
    }
    @localApi("playerRoute")
    openEgg(index, gamRouteData?: GameRouteData) {
        // let { player, time, dayTime, random } = gamRouteData
        // if (!player.luck.xunbao.eggs[index].haveGift) {
        //     return { err: 1 }
        // }
        // player.luck.xunbao.eggs[index].haveGift = false
        // let gift = player.luck.xunbao.eggs[index].gift
        // //将获取的奖励放进背包
        // bagHandle.addItem(player.bag, gift['getItem'], gift['amount'])
        // return { err: 0, data: gift }
    }
    //升级科研设备
    @localApi("playerRoute")
    researchEquipmentLvlUp(index: number, gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random } = gameRouteData
        let research = player.research
        let lvl = research.equipmentLvls[index]
        let researchConfig = gameConfigHandle.gameConfig.research
        let lvlMax = researchConfig.equipmentLvlMax
        if (lvl >= lvlMax) {
            return { err: 1 }
        }
        let needconfig = gameConfigHandle.gameConfig.need.researchEquipmentLvlUpNeed
        let res = gameUtils.useNeedResource(player, needconfig, lvl)
        if (res != 0) {
            return { err: 2 }
        }
        research.equipmentLvls[index]++

        return { err: 0 }
    }
    //升级科研设备
    @localApi("playerRoute")
    newResearchEquipmentLvlUp(equipid: number, gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random } = gameRouteData
        let research = player.research
        let lvl = research.newEquipmentLvls[equipid] || 0
        let researchConfig = gameConfigHandle.gameConfig.research
        let lvlMax = researchConfig.equipmentLvlMax
        if (lvl >= lvlMax) {
            return { err: 1 }
        }
        let needconfig = gameConfigHandle.gameConfig.need.newResearchEquipmentLvlUpNeed
        let res = gameUtils.useNeedResource(player, needconfig, lvl)
        if (res != 0) {
            return { err: 2 }
        }
        research.newEquipmentLvls[equipid] = lvl + 1
        let researchItemConfig = gameConfigHandle.configByID[equipid]
        let value = utils.getIncValues(researchItemConfig.incValues, research.newEquipmentLvls[equipid])
        research.researchEquipmentAttris[researchItemConfig.researchType] = value
        return { err: 0 }
    }
    @localApi("playerRoute")
    researchLvlUp(gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random } = gameRouteData
        let research = player.research
        let lvl = research.lvl
        let lvlMax = gameConfigHandle.gameConfig.research.equipmentLvlMax
        if (lvl >= lvlMax) {
            return { err: 1 }
        }
        for (let i = 0; i < research.equipmentLvls.length; i++) {
            if (research.equipmentLvls[i] <= lvl) {
                return { err: 2 }
            }
        }
        research.lvl++
        research.point += gameConfigHandle.gameConfig.research.pointPerLvl
        return { err: 0 }
    }
    //升级训练
    @localApi("playerRoute")
    immuneUp(index: number, gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random } = gameRouteData
        let research = player.research
        let researchConfig = gameConfigHandle.gameConfig.research
        let lvl = research.immuneList[index] || 0
        let lvl1 = research.immuneList[index - 1] || 0
        let lvlMax = researchConfig.immuneMaxLvl
        if (lvl >= lvlMax) {
            return { err: 1 }
        }
        if (index >= 1 && lvl >= lvl1) {
            return { err: 2 }
        }

        let needconfig = gameConfigHandle.gameConfig.need.immuneUpNeed
        let res = gameUtils.useNeedResource(player, needconfig, lvl + index)
        if (res != 0) {
            return { err: 3 }
        }
        research.immuneList[index] = lvl + 1
        return { err: 0 }
    }
    //训练升星
    @localApi("playerRoute")
    immuneStarUp(index: number, gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random } = gameRouteData
        let research = player.research
        let researchConfig = gameConfigHandle.gameConfig.research
        let lvl = research.immuneStarList[index] || 0
        let lvl1 = research.immuneStarList[index - 1] || 0
        let lvlMax = researchConfig.immuneMaxStar
        if (lvl >= lvlMax) {
            return { err: 1 }
        }
        if (index >= 1 && lvl >= lvl1) {
            return { err: 2 }
        }

        let needconfig = gameConfigHandle.gameConfig.need.immuneStarUpNeed
        let res = gameUtils.useNeedResource(player, needconfig, lvl + index)
        if (res != 0) {
            return { err: 3 }
        }
        research.immuneStarList[index] = lvl + 1
        return { err: 0 }
    }

    //重置免疫单位
    @localApi("playerRoute")
    resetImmune(id: number, gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random } = gameRouteData
        let research = player.research
        let lvl = research.immuneList[id] || 0
        if (lvl == 0) {
            return { err: 2 }
        }
        let needDiamond = gameConfigHandle.gameConfig.research.resetImmuneNeedDiamond
        if (player.itemInfo.diamond < needDiamond) {
            return { err: 1 }
        }
        player.itemInfo.diamond -= needDiamond
        research.point += lvl
        research.immuneList[id] = 0
        return { err: 0 }
    }
    //领取常规任务奖励
    @localApi("playerRoute")
    getReward(taskType: NormlaTaskType, gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random } = gameRouteData
        let taskConfig = gameConfigHandle.gameConfig.task
        let taskItem = taskConfig.list.find(item => item.type == taskType)
        if (!taskItem) {
            return { err: 50 }
        }
        let { isPass } = taskHandle.isTaskPass(player, taskItem)
        if (!isPass) {
            return { err: 1 }//任务未完成
        }

        //奖励内容
        player.itemInfo.diamond += taskConfig.normalTaskRewardDiamond
        player.task.doneAmount++
        player.task.list[taskItem.type] = (player.task.list[taskItem.type] || 0) + 1
        return { err: 0 }
    }
    //领取日常任务奖励
    @localApi("playerRoute")
    getDayMessionGift(id: number, gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random } = gameRouteData
        if (player.task.getDayMessionGift[id]) {
            return { err: 1 }//已经领取
        }
        if (!taskHandle.isDayMessionPass(id, player)) {
            return { err: 2 }
        }
        player.task.getDayMessionGift[id] = true
        let getDiamond = gameConfigHandle.gameConfig.task.dayMessionDiamond
        player.itemInfo.diamond += getDiamond
        let gift = `获得: 钻石x${getDiamond}`
        return { err: 0, data: gift }
    }
    //领取日常任务彩蛋奖励
    @localApi("playerRoute")
    getDayMessionEggGift(index: number, gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random, } = gameRouteData
        let dayMessionConfig = gameConfigHandle.gameConfig.task.dayMessionEggGift
        let scoreNeed = dayMessionConfig.progress[index]
        let gift = dayMessionConfig.gifts[index]
        let amount = gift.amount
        let id = gift.itemId
        if (player.task.dayMessionGiftsState[index]) {
            return { err: 2 }
        }
        let score = taskHandle.getDayMessionProgress(player).score
        if (score < scoreNeed) {
            return { err: 1 }
        }
        if (typeof id == 'number') {
            bagHandle.addItem(player.bag, id, amount)
        } else {
            //金币 经验就获得 1分钟挂机收益*任务倍率
            if (id == 'gold') {
                amount = adventureHandle.getGoldResoureOriginAdd(player) * amount
                player.itemInfo[id] += amount
            } else {
                player.itemInfo[id] += amount
            }
        }
        player.task.dayMessionGiftsState[index] = true
        return { err: 0, data: { itemId: id, amount } }
    }

    //病毒疫苗升级
    @localApi("playerRoute")
    vaccineLvlup(index: number, gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random } = gameRouteData
        let needconfig = gameConfigHandle.gameConfig.need
        let researchConfig = gameConfigHandle.gameConfig.research
        let vaccineItemConfig = researchConfig.vaccineMonsterList[index]
        let monsterID = vaccineItemConfig.monsterID
        let monsterItemConfig = gameConfigHandle.configByID[monsterID]
        let monsterTypeIndex = monsterItemConfig.monsterTypeIndex
        let vaccineLvl = player.research.vaccines[monsterTypeIndex] || 0
        let vaccineLvlMax = gameConfigHandle.gameConfig.research.vaccineMaxLvl
        if (vaccineLvl >= vaccineLvlMax) {
            return { err: 1 }
        }

        let limits = []
        vaccineItemConfig.limit.forEach((limit, i) => {
            let lvl = player.research.vaccines[monsterTypeIndex] || 0
            let limitLvl = utils.getIncValues(limit.limitLvl, lvl)
            let equipmentLvl = player.research.equipmentLvls[limit.equipmentId] || 0
            if (equipmentLvl < limitLvl) {
                limits.push({ equipmentId: limit.equipmentId, limitLvl })
            }
        })
        if (limits.length > 0) {
            return { err: 3, data: limits }
        }

        let res = gameUtils.useNeedResource(player, needconfig.vaccinesLvlup, (player.research.vaccines[monsterTypeIndex] || 0) + monsterItemConfig.monsterTypeIndex)
        if (res != 0) {
            return { err: 2 }
        }

        if (!player.research.vaccines[monsterTypeIndex]) {
            player.research.vaccines[monsterTypeIndex] = 0
        }
        player.research.vaccines[monsterTypeIndex]++
        return { err: 0 }
    }
    //记录今日副本挑战次数
    @localApi("playerRoute")
    instanceDataSave(id: number, gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random } = gameRouteData

        // console.log('player.task.instanceTimes=',player.task.instanceTimes)
        return { err: 0 }
    }

    //宝石共鸣升级
    @localApi("playerRoute")
    upGemTeamLvl(gameRouteData?: GameRouteData) {
        let { player, time, dayTime, random } = gameRouteData
        let lvl = player.gemTeamLvl || 0
        let lvlMax = gameConfigHandle.gameConfig.gem.gemTeamLvlMax
        if (lvl >= lvlMax) {
            return { err: 1 }//等级已达上限
        }
        let canUpLvl = gemHandle.getGemTeamLvlMax(player)
        if (lvl >= canUpLvl) {
            return { err: 2 }//镶嵌的宝石等级不足
        }
        let needConfig = gameConfigHandle.gameConfig.need.gemTeamLvlUp
        let res = gameUtils.useNeedResource(player, needConfig, lvl)
        if (res !== 0) {
            return { err: 3 }//材料不足
        }
        player.gemTeamLvl = lvl + 1
        return { err: 0 }
    }
}

let playerRoute: PlayerRoute = new PlayerRoute()
export default playerRoute